﻿using System;
using HISModels.ViewModel;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using System.IO;
using KeanuMvc.Reference;
using HIS.Utils.Securities;
using HIS.Utils;
using HISModels.Entities;
using System.Configuration;
using Newtonsoft.Json.Linq;

namespace HIS.Controllers.Master {

    public class ItemSubCategories : HIS.Controllers.AppBaseController {

        #region Fields
        private string strAction = string.Empty;
        private string strNotification = string.Empty;
        private RefItemSubCategory refItemSubCategory = null;
        #endregion

        #region Items Groups
        public ItemSubCategories() {
            Data.Add("Pagetitle", "Item Sub Category");
            Data.Add("Notification", strNotification);
        }

        [Authorization(RoleAction = "master-items")]
        public override void Index() {
            try {
                Data.Add("categoryId", HttpContext.Current.Request["catid"]);
                RenderFile("master\\items\\itemsubcategories.html");
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

        [Authorization(RoleAction = "master-items")]
        public void TableList() {
            try {
                string strJson = string.Empty;
                string sEcho = HttpContext.Current.Request["sEcho"];
                string codevalue = HttpContext.Current.Request["codevalue"].NullSafeToString();
                string namevalue = HttpContext.Current.Request["namevalue"].NullSafeToString();

                string category = HttpContext.Current.Request["category"].NullSafeToString();
                string ssearch = "code=" + codevalue + ";nama=" + namevalue + ";category=" + category;

                PostDataTablesNet pagingSearch = new PostDataTablesNet();
                pagingSearch.iDisplayLength = Convert.ToInt32(HttpContext.Current.Request["iDisplayLength"]);
                pagingSearch.iDisplayStart = Convert.ToInt32(HttpContext.Current.Request["iDisplayStart"]);
                pagingSearch.sEcho = Convert.ToInt32(HttpContext.Current.Request["sEcho"]);
                //pagingSearch.sSearch = HttpContext.Current.Request["sSearch"];
                if (!string.IsNullOrEmpty(ssearch)) {
                    pagingSearch.sSearch = ssearch;
                } else { pagingSearch.sSearch = Convert.ToString(HttpContext.Current.Request["sSearch"]); }
                pagingSearch.sSearch = ssearch;
                //
                string strUri = string.Empty;
                strUri = Global.ServiceUriDictionary["itemsubcategorypaging"] + Global.ServiceUriDictionary["requestformat"];
                StringReader stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(pagingSearch));

                strJson = stringReader.ReadToEnd();
                stringReader.Dispose();
                base.RestService.Dispose();
                HttpContext.Current.Response.Write(strJson);

            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

        [Authorization(RoleAction = "master-items")]
        public void EditGroups() {
            StringReader stringReader = null;
            /// Get id record from querystring
            int id = 0;
            try {
                id = Convert.ToInt32(HttpContext.Current.Request["id"]);
            } catch {
                /// Throw to list if something goes wrong
                GoToUrl("itemsubcategories/"); return;
            }

            try {
                ///Set Rest Url///
                string strUri = Global.ServiceUriDictionary["itemsubcategory"] + id + Global.ServiceUriDictionary["requestformat"];
                ///Get Rest///
                stringReader = base.RestService.GetJson(strUri);
                ///Deserialize json response to object///
                refItemSubCategory = JsonConvert.DeserializeObject<RefItemSubCategory>(stringReader.ReadToEnd());
                Data.Add("ddlLocationAE", DropDownCategory(refItemSubCategory.ItemCategoryId.NullSafeToString()));
                ///Set variable for rendering on view HTML///
                Data["Pagetitle"] += " :: Edit Item Sub Category";
                Data.Add("refItemSubCategory", refItemSubCategory);
                Data.Add("IsCreate", "false");
                Data["Notification"] = strNotification;
            } catch (Exception ex) {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            } finally {
                RenderFile("Master\\items\\editsubcategories.html");
                if (stringReader != null) stringReader.Dispose();
                base.RestService.Dispose();
            }
        }

        [Authorization(RoleAction = "master-items")]
        public void DeleteItemGroups() {
            StringReader stringReader = null;
            int id = 0;
            try {
                id = Convert.ToInt32(HttpContext.Current.Request["id"]);
            } catch {
                GoToUrl("itemgroups/");
                return;
            }

            try {
                refItemSubCategory = new HISModels.Entities.RefItemSubCategory();
                string strUri = Global.ServiceUriDictionary["itemsubcategory"] + Global.ServiceUriDictionary["requestformat"];

                stringReader = base.RestService.DeleteJson(strUri, JsonConvert.SerializeObject(id));
                var a = JsonConvert.DeserializeObject<RefItemSubCategory>(stringReader.ReadToEnd());
                if (strNotification == string.Empty) strNotification = Helper.SuccessMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                Data["Notification"] = strNotification;

            } catch (Exception ex) {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            } finally {
                HttpContext.Current.Response.Redirect(Data["rooturl"] + "master/itemsubcategories/");
                base.RestService.Dispose();
            }
        }

        [Authorization(RoleAction = "master-items")]
        public void SaveItemGroups() {
            StringReader stringReader = null;
            string strUri = string.Empty;
            try {
                refItemSubCategory = new RefItemSubCategory(); Utils.Helper.SetNullToEmptyString(refItemSubCategory);
                if (HttpContext.Current.Request["IsCreate"] != "true") {
                    int id = 0;
                    try {
                        id = Convert.ToInt32(HttpContext.Current.Request["idem"]);
                    } catch { }
                    strUri = Global.ServiceUriDictionary["itemgroup"] + id + Global.ServiceUriDictionary["requestformat"];
                    ///Get Rest///
                    stringReader = base.RestService.GetJson(strUri);
                    refItemSubCategory = JsonConvert.DeserializeObject<RefItemSubCategory>(stringReader.ReadToEnd());
                }

                refItemSubCategory.PostHandler<HISModels.Entities.RefItemSubCategory>();
                strUri = Global.ServiceUriDictionary["itemsubcategory"] + Global.ServiceUriDictionary["requestformat"];

                if (HttpContext.Current.Request["IsCreate"] == "true") {
                    stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(refItemSubCategory));
                } else {
                    stringReader = base.RestService.PutJson(strUri, JsonConvert.SerializeObject(refItemSubCategory));
                }
                string temp = stringReader.ReadToEnd();


                refItemSubCategory = JsonConvert.DeserializeObject<RefItemSubCategory>(temp);

                if (refItemSubCategory != null) {
                    strNotification = Helper.SuccessMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                } else {
                    strNotification = Helper.ErrorMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                }


                strNotification = "{\"strNotification\": \"" + strNotification + "\"}";
                HttpContext.Current.Response.Write(strNotification);

            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            } finally {
                base.RestService.Dispose();
            }
        }

        [Authorization(RoleAction = "master-items")]
        public void CreateSubCategories() {

            try {
                Data["Pagetitle"] += " :: Add Item Sub Category";
                refItemSubCategory = new HISModels.Entities.RefItemSubCategory() { CodeValue = string.Empty, NameValue = string.Empty };
                Data.Add("ddlLocationAE", DropDownCategory(refItemSubCategory.ItemCategoryId.NullSafeToString()));
                refItemSubCategory.SetNullToEmptyString();
                Data.Add("refItemSubCategory", refItemSubCategory);
                Data.Add("IsCreate", "true");
                Data["Notification"] = strNotification;

            } catch (Exception ex) {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            } finally {
                RenderFile("Master\\items\\editsubcategories.html");
                base.RestService.Dispose();
            }
        }

        public string DropDownCategory(string Selected) {
            StringReader stringReaderDropDown = null;
            string strResult = string.Empty;
            string strUri = Global.ServiceUriDictionary["itemcategorylist"] + Global.ServiceUriDictionary["requestformat"];
            try {
                stringReaderDropDown = base.RestService.GetJson(strUri);
                List<RefItemCategory> listHu = JsonConvert.DeserializeObject<List<RefItemCategory>>(stringReaderDropDown.ReadToEnd());
                List<object[]> activeArr = new List<object[]>();
                foreach (RefItemCategory item in listHu) activeArr.Add(new object[] { item.Id, item.CodeValue + " - " + item.NameValue });
                strResult = KeanuMvc.Reference.Html.DropDown("category", string.Empty, activeArr, Selected);
                activeArr.Clear();
                activeArr = null;
            } catch {
            } finally {
                stringReaderDropDown.Dispose();
            }
            return strResult;
        }

        public string DropDownRoleCategory(string Selected) {
            StringReader stringReaderDropDown = null;
            string strResult = string.Empty;
            string Name = string.Empty;
            string strUri = "";
            strUri = Global.ServiceUriDictionary["itemcategorylist"] + Global.ServiceUriDictionary["requestformat"];
            try {
                stringReaderDropDown = base.RestService.GetJson(strUri);
                List<HISModels.Entities.RefItemCategory> listSp = JsonConvert.DeserializeObject<List<RefItemCategory>>(stringReaderDropDown.ReadToEnd());
                List<object[]> activeArr = new List<object[]>();

                activeArr.Add(new object[] { -1, Name = "- All Category -" });

                foreach (RefItemCategory item in listSp) activeArr.Add(new object[] { item.Id, Name = item.NameValue });

                strResult = KeanuMvc.Reference.Html.DropDown("category", string.Empty, activeArr, Selected);
                activeArr.Clear();
                activeArr = null;
            } catch {
            } finally {
            }
            return strResult;
        }

        public string DropDownRoleLocation(string Selected) {
            StringReader stringReaderDropDown = null;
            string strResult = string.Empty;
            string Name = string.Empty;
            string strUri = "";
            strUri = Global.ServiceUriDictionary["itemcategory"] + Global.ServiceUriDictionary["requestformat"];
            try {
                stringReaderDropDown = base.RestService.GetJson(strUri);
                List<HISModels.Entities.RefItemCategory> listSp = JsonConvert.DeserializeObject<List<RefItemCategory>>(stringReaderDropDown.ReadToEnd());
                List<object[]> activeArr = new List<object[]>();

                activeArr.Add(new object[] { -1, Name = "- All Location -" });

                foreach (RefItemCategory item in listSp) activeArr.Add(new object[] { item.Id, Name = item.NameValue });

                strResult = KeanuMvc.Reference.Html.DropDown("itemcategoryid", string.Empty, activeArr, Selected);
                activeArr.Clear();
                activeArr = null;
            } catch {
            } finally {
            }
            return strResult;
        }
        #endregion

    }

}

